<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <el-card>
    <el-row>
      <el-col>
        <el-button type="primary" @click="addRoleV">添加角色</el-button>
      </el-col>
    </el-row>
    <el-table :data="rolesList" stripe style="width: 100%" border row-key="id">
      <el-table-column type="expand">
        <template  v-slot:default="scope">
          <el-row :class="['bdbottom', i1 === 0 ? 'bdtop': null,'vcenter']" v-for="(item1 , i1) in scope.row.children" :key="item1.id">
            <!--          一级-->
            <el-col :span="5">
              <el-tag :size="'default'" closable @close="removeRightById(scope.row,scope.row.id ,item1.id)" >{{item1.authName}}</el-tag>
              <el-icon><ArrowRightBold /></el-icon>
            </el-col>
<!--              <el-tag :size="'default'">{{item1.children}}</el-tag>-->
            <!--          一级和三级-->
            <el-col :span="19">
              <el-row :class="[i2 === 0 ? null : 'bdtop','vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag type="success" closable @close="removeRightById(scope.row,scope.row.id ,item2.id)">{{item2.authName}}</el-tag>
                  <el-icon><ArrowRightBold /></el-icon>
                </el-col>
                <el-col :span="18">
                  <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,scope.row.id ,item3.id)">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
            <hr>
          </el-row>

        </template>
      </el-table-column>
      <el-table-column label="#" type="index" width="120"/>
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="roleDesc" label="角色描述" />
      <el-table-column label="操作" width="300">
        <template v-slot:default="scope">
          <el-button type="primary" :icon="Edit" size="small" @click="showEditDialog(scope.row.id)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="removeRole(scope.row.id) ">删除</el-button>
          <el-button type="warning" :icon="Setting" size="small" @click="showSetRightDialog(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>

    </el-table>

  </el-card>


  <el-dialog
      v-model="addRoleDialogVisible"
      title="添加角色"
      width="30%"
      @close="addRoleDialogClosed"
  >

    <el-form
        ref="addRoleFormRef"
        :model="addRoleForm"
        :rules="addRoleFormRules"
        label-width="120px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addRoleForm.roleName"/>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addRoleForm.roleDesc"/>
      </el-form-item>
    </el-form>
<!--    表单 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRole">
          添加
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="editRoleDialogVisible"
      title="编辑角色"
      width="30%"
      @close="editRoleDialogClosed"
  >

    <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        :rules="editRoleFormRules"
        label-width="120px"
    >
      <el-form-item label="角色ID" prop="id" >
        <el-input v-model="editRoleForm.id" disabled/>
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="editRoleForm.roleName"/>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="editRoleForm.roleDesc"/>
      </el-form-item>

    </el-form>
    <!--    表单 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editRole">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="setRightDialogVisible"
      title="分配权限"
      width="30%"
      @close="setRightDialogClosed"
  >
    <el-tree :data="rightsList" :props="RightTreeProps"
             show-checkbox default-expand-all node-key="id"
             :default-checked-keys="defKeys"
             ref="RightTreeRef"
    />

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>



</template>

<script>
import {Delete, Edit, Setting} from "@element-plus/icons-vue/global";

export default {
  name: "Roles",
  computed: {
    Setting() {
      return Setting
    },
    Edit() {
      return Edit
    },
    Delete(){
      return Delete
    }
  },
  data(){
    return{
      rolesList : [],
      addRoleDialogVisible : false,
      editRoleDialogVisible: false,
      setRightDialogVisible: false,
      rightsList : [],
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      roleId: '',
      editRoleForm: {
        id:'',
        roleName: '',
        roleDesc: '',
      },
      addRoleFormRules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 3, max: 10, message: '角色名称的长度在 3 到 8 之间', trigger: 'blur'},
        ],
        roleDesc:[
          {required:true, message: '请输入角色描述', trigger: 'blur'},
          {max: 50, message: '角色描述的长度需要小于50字符', trigger: 'blur'},
        ]
      },
      editRoleFormRules:{

      },
      RightTreeProps:{
        children: 'children',
        label: 'authName',
      },
      defKeys:[105, 116]
    }
  },
  created() {
      this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const {data: res} = await this.$http.get('roles');
      this.rolesList = res.data
      console.log(res)
      return (res.meta.status === 200) ? null : this.$message.error(res.meta.msg);
    },
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    editRoleDialogClosed(){
      this.$refs.editRoleFormRef.resetFields()
    },
    setRightDialogClosed(){
      this.defKeys = []
    },
    addRoleV() {
      this.addRoleDialogVisible = true
    },
    async addRole() {
      await this.$refs.addRoleFormRef.validate(async v => {
        if (!v) {
          return this.$message.error("信息格式错误")
        } else {
          const {data: res} = await this.$http.post('roles', this.addRoleForm);
          if(res.meta.status === 201){
            await this.getRolesList()
            this.addRoleDialogVisible = false
          }
          await this.getRolesList();
          return (res.meta.status === 201) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);
        }
      })
    },
    async showEditDialog(id) {
      const {data: res} = await this.$http.get(`roles/${id}`);
      this.editRoleForm = res.data
      this.editRoleForm.id = res.data.roleId;
      this.editRoleDialogVisible = true
    },
    async editRole(){
      await this.$refs.editRoleFormRef.validate(async v => {
        if (!v) return
        else {
          const {data: res} = await this.$http.put(`roles/${this.editRoleForm.id}`, this.editRoleForm);

            await this.getRolesList()

            this.editRoleDialogVisible = false

            return (res.meta.status === 200) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);

        }
      })
    },
    removeRole(id){
      this.$confirm(
          '此操作将永久删除角色, 请确认！',
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {
        const {data: res} = await this.$http.delete(`roles/${id}`);
        if(res.meta.status !== 200){
          this.$message.warning(res.meta.msg)
        }else{
          await this.getRolesList()
          this.$message.success(res.meta.msg)
        }

      }).catch(() => {
        this.$message.info('已取消删除操作');
      })
    },
    async removeRightById(role,roleId,rightId){
      this.$confirm(
          '此操作将永久删除权限, 请确认！',
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {

        const {data: res} = await this.$http.delete(`roles/${roleId}/rights/${rightId}`);

        role.children = res.data

        // await this.getRolesList()

        return (res.meta.status === 200) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);

      }).catch(() => {
        this.$message.info('已取消删除操作');
      })
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      const {data: res} = await this.$http.get('rights/tree')
      this.rightsList = res.data
      // console.log(this.rightsList)
      this.defKeys = []
      this.getLeafKeys(role, this.defKeys)

      this.setRightDialogVisible = true
      return (res.meta.status === 200) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);
    },
    async allotRights() {
      const keys = [
        ...this.$refs.RightTreeRef.getCheckedKeys(),
        ...this.$refs.RightTreeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')

      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids:idStr
      })
      await this.getRolesList()
      this.setRightDialogVisible = false
      return (res.meta.status === 200) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);
    },

    getLeafKeys(node, arr){
      if(!node.children){
        arr.push(node.id)
        return;
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    }

  }
}
</script>

<style scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}

.vcenter{
  display: flex;
  align-items: center;
}
</style>